<?php

namespace Admin\Model;

use Think\Model\RelationModel;

/**
 * 权限管理之角色模型类
 * Class RoleModel
 * @package Admin\Model
 */
class RoleModel extends RelationModel
{
    protected $insertFields = array('role_name');
    protected $updateFields = array('id', 'role_name');
    protected $_validate = array(
        array('role_name', 'require', '角色名称不能为空！', 1, 'regex', 3),
        array('role_name', '1,30', '角色名称的值最长不能超过 30 个字符!', 1, 'length', 3),
    );

    /**
     * @inheritdoc
     */
    protected function _after_insert($data, $option)
    {
        $priId = I('post.pri_id');
        if ($priId) {
            $rpModel = M('RolePrivilege');
            foreach ($priId as $k => $v) {
                $rpModel->add(array(
                    'pri_id' => $v,
                    'pri_role_id' => $data['id'],
                ));
            }
        }
    }

    /**
     * @inheritdoc
     */
    protected function _before_update(&$data, $option)
    {
        // 先清除原来的权限
        $rpModel = M('RolePrivilege');
        $rpModel->where(array('pri_role_id' => array('eq', $option['where']['id'])))->delete();
        // 接收表单重新添加一遍
        $priId = I('post.pri_id');
        if ($priId) {
            foreach ($priId as $k => $v) {
                $rpModel->add(array(
                    'pri_id' => $v,
                    'pri_role_id' => $option['where']['id']
                ));
            }
        }
    }

    /**
     * @inheritdoc
     */
    protected function _before_delete($option)
    {
        // 验证是否有管理帐号属于该角色
        $arModel = M('AdminRole');
        $has = $arModel->where(array('role_id' => array('eq', $option['where']['id'])))->count();
        if ($has > 0) {
            $this->error = '有管理员属于这个角色，无法删除！';
            return false;
        }
        //删除该角色所拥有的全部权限
        $rpModel = M('RolePrivilege');
        $rpModel->where(array('role_id' => array('eq', $option['where']['id'])))->delete();
        return true;
    }
}